from typing import List, Optional
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import and_, func
from app.database import get_db
from app.models.score import Score
from app.models.exam import Exam
from app.models.user import User, UserRole
from app.models.question import Question
from app.models.answer import Answer
from app.schemas.score import ScoreResponse, ScoreDetail, ScoreRank
from app.schemas.answer import ExamSubmit, AnswerSubmit
from app.auth import get_current_active_user, get_current_teacher

router = APIRouter()

@router.get("/", response_model=List[ScoreResponse])
async def get_scores(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    exam_id: Optional[int] = Query(None, description="考试ID筛选"),
    user_id: Optional[int] = Query(None, description="用户ID筛选"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取成绩列表"""
    query = db.query(Score)
    
    # 权限过滤
    if current_user.role == UserRole.STUDENT:
        query = query.filter(Score.user_id == current_user.id)
    elif current_user.role == UserRole.TEACHER:
        # 教师只能查看自己创建的考试的成绩
        exam_ids = db.query(Exam.id).filter(Exam.created_by == current_user.id)
        query = query.filter(Score.exam_id.in_(exam_ids))
    
    if exam_id:
        query = query.filter(Score.exam_id == exam_id)
    
    if user_id:
        query = query.filter(Score.user_id == user_id)
    
    scores = query.order_by(Score.submitted_at.desc()).offset(skip).limit(limit).all()
    
    # 添加考试信息
    result = []
    for score in scores:
        exam = db.query(Exam).filter(Exam.id == score.exam_id).first()
        user = db.query(User).filter(User.id == score.user_id).first()
        score_dict = {
            **score.__dict__,
            "exam": {
                "id": exam.id,
                "title": exam.title
            },
            "user": {
                "id": user.id,
                "username": user.username,
                "full_name": user.full_name
            }
        }
        result.append(score_dict)
    
    return result

@router.get("/{score_id}", response_model=ScoreDetail)
async def get_score_detail(
    score_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取成绩详情"""
    score = db.query(Score).filter(Score.id == score_id).first()
    if not score:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="成绩不存在"
        )
    
    # 权限检查
    if current_user.role == UserRole.STUDENT and score.user_id != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能查看自己的成绩"
        )
    
    if current_user.role == UserRole.TEACHER:
        exam = db.query(Exam).filter(Exam.id == score.exam_id).first()
        if exam and exam.created_by != current_user.id:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="只能查看自己创建的考试的成绩"
            )
    
    # 获取答案详情
    answers = db.query(Answer).filter(
        and_(Answer.user_id == score.user_id, Answer.exam_id == score.exam_id)
    ).all()
    
    # 添加题目信息
    answers_with_questions = []
    for answer in answers:
        question = db.query(Question).filter(Question.id == answer.question_id).first()
        answers_with_questions.append({
            **answer.__dict__,
            "question": {
                "id": question.id,
                "title": question.title,
                "question_type": question.question_type,
                "score": question.score,
                "correct_answer": question.correct_answer
            }
        })
    
    return {
        **score.__dict__,
        "answers": answers_with_questions
    }

@router.post("/submit", response_model=ScoreResponse)
async def submit_exam(
    exam_id: int,
    submit_data: ExamSubmit,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """提交考试"""
    # 检查考试
    exam = db.query(Exam).filter(Exam.id == exam_id).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 检查考试状态
    now = datetime.utcnow()
    if exam.status != "published" or now < exam.start_time or now > exam.end_time:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="当前时间不能提交该考试"
        )
    
    # 检查是否已经提交过
    existing_score = db.query(Score).filter(
        and_(Score.user_id == current_user.id, Score.exam_id == exam_id)
    ).first()
    
    if existing_score:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已经提交过该考试"
        )
    
    # 计算成绩
    total_score = 0.0
    correct_count = 0
    wrong_count = 0
    
    # 保存答案并计算分数
    for answer_submit in submit_data.answers:
        question = db.query(Question).filter(Question.id == answer_submit.question_id).first()
        if not question:
            continue
        
        is_correct = answer_submit.answer.strip() == question.correct_answer.strip()
        score = question.score if is_correct else 0.0
        
        if is_correct:
            correct_count += 1
        else:
            wrong_count += 1
        
        total_score += score
        
        # 保存答案
        db_answer = Answer(
            user_id=current_user.id,
            exam_id=exam_id,
            question_id=answer_submit.question_id,
            answer_content=answer_submit.answer,
            is_correct=is_correct,
            score=score
        )
        db.add(db_answer)
    
    # 保存成绩
    db_score = Score(
        user_id=current_user.id,
        exam_id=exam_id,
        score=total_score,
        correct_count=correct_count,
        wrong_count=wrong_count,
        total_count=len(submit_data.answers),
        start_time=now,  # 这里应该记录实际开始时间
        end_time=now,
        duration=0  # 这里应该计算实际用时
    )
    db.add(db_score)
    db.commit()
    db.refresh(db_score)
    
    return db_score

@router.get("/rank/{exam_id}", response_model=List[ScoreRank])
async def get_exam_rank(
    exam_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_teacher)
):
    """获取考试成绩排名"""
    exam = db.query(Exam).filter(Exam.id == exam_id).first()
    if not exam:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="考试不存在"
        )
    
    # 检查权限
    if current_user.role == UserRole.TEACHER and exam.created_by != current_user.id:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能查看自己创建的考试的排名"
        )
    
    scores = db.query(Score).filter(Score.exam_id == exam_id).order_by(Score.score.desc(), Score.submitted_at.asc()).all()
    
    ranks = []
    for index, score in enumerate(scores):
        user = db.query(User).filter(User.id == score.user_id).first()
        ranks.append(ScoreRank(
            user_id=user.id,
            username=user.username,
            full_name=user.full_name,
            score=score.score,
            duration=score.duration,
            submitted_at=score.submitted_at,
            rank=index + 1
        ))
    
    return ranks